define(['jquery', 'bootstrap', 'backend', 'form', 'addtabs', 'table', 'echarts', 'echarts-theme', 'template','filesaver'], function ($, undefined, Backend, Form, Datatable, Table, Echarts, undefined, Template) {

    var Controller = {
        index: function () {
            $(".datetimerange").on("blur", function () {
                var type = $(this).attr('data-type');
                var title = $(this).attr('data-title');
                Fast.api.ajax({
                    url: 'dashboard/circle',
                    data: {
                        startdate: $(this).val(),
                        type: type
                    }
                }, function (data) {
                    Controller.api.charts(data, type, title);
                    return false;
                });
            });
            $(document).on("click", ".btn-filter", function () {
                var label = $(this).text();
                var type = $(this).attr('data-type');
                var obj = $(".datetimerange[data-type='" + type + "']").data("daterangepicker");

                var dates = obj.ranges[label];
                obj.startDate = dates[0];
                obj.endDate = dates[1];

                obj.clickApply();
            });
            $(document).on("click", ".btn-refresh", function () {
                var type = $(this).attr('data-type');
                if (type) {
                    $(".datetimerange[data-type='" + type + "']").trigger("blur");
                }
            });
            $($('.nav-tabs li.active').find('a').attr('href')).find('.datetimerange').each(function () {
                var type = $(this).attr('data-type');
                if (type) {
                    $(".datetimerange[data-type='" + type + "']").trigger("blur");
                }
            });
            $('.nav-tabs li').click(function () {
                $($(this).find('a').attr('href')).find('.datetimerange').each(function () {
                    var type = $(this).attr('data-type');
                    if (type) {
                        $(".datetimerange[data-type='" + type + "']").trigger("blur");
                    }
                });
            });
            Form.api.bindevent($("form[role=form]"));
            $(".datetimerange").trigger("blur");
        },
        api: {
            charts: function (data, type, title) {
                var series = [];
                var i = 0;
                for (var o in data.series) {
                    var element = data.series[o];
                    series.push({
                        name: data.fieldtextdata[i],
                        type: 'line',
                        smooth: true,
                        areaStyle: {
                            normal: {}
                        },
                        lineStyle: {
                            normal: {
                                width: 1.5
                            }
                        },
                        data: element,
                    });
                    i++;
                }
                var myChart = Echarts.init(document.getElementById('echarts_' + type), 'walden');
                myChart.resize();
                // 指定图表的配置项和数据
                var option = {
                    title: {
                        text: title,
                        subtext: ''
                    },
                    tooltip: {
                        trigger: 'axis',
                    },
                    legend: {
                        data: data.fieldtextdata
                    },
                    toolbox: {
                        show : true,
                        feature : {
                            dataView: {
                                show: true,
                                lang: ['数据视图', '关闭', '导出Excel'],
                                //optionToContent为重画表格的函数
                                optionToContent: function(opt){
                                    //axisData是你想定义的表格第一列的数据，我这里设置为柱形图的x轴数据
                                    var axisData = opt.xAxis[0].data;
                                    //tAxis[0]为你想定义的表格第一行的数据
                                    var txisData = opt.series;
                                    var series = opt.series;
                                    //表头
                                    var tdHeads = '<td  style="padding: 0 10px" id="table_echarts_'+type+'"></td>';
                                    var tdBodys = '';
                                    var nameData = txisData;
                                    for (var i = 0; i < nameData.length ; i++) {
                                        tdHeads += '<td style="padding: 0 10px">' + nameData[i].name + '</ td >';
                                    }
                                    var table = '<table id="Mytable" border="1" class="table table-bordered table-striped table-hover" style="width:100%;text-align:center" ><tbody><tr>' + tdHeads + ' </tr>';
                                    for (var i = 0, l = axisData.length; i < l; i++) {
                                        for (var j = 0; j < series.length; j++) {
                                            var temp = series[j].data[i];
                                            if (temp != null && temp != undefined) {
                                                tdBodys += '<td>' + temp + '</td>';
                                            } else {
                                                tdBodys += '<td></td>';
                                            }
                                        }
                                        table += '<tr><td style="padding: 0 10px">' + axisData[i] + '</td>' + tdBodys + '</tr>';
                                        tdBodys = '';
                                    }

                                    table += '</tbody></table>';
                                    console.log(table)
                                    return table;
                                },
                                //contentToOption为重写“刷新”按钮的语句
                                contentToOption: function (HTMLDomElement, opt) {
                                    // var et=XLSX.utils.table_to_book(document.getElementById('echarts_' + type),{raw:true})
                                    //      var table1 = document.querySelector('table_echarts_' + type);
                                    //      console.log(table1);
                                    // var sheet = XLSX.utils.table_to_sheet(document.getElementById('table_echarts_' + type));//将一个table对象转换成一个sheet对象
                                    let et = XLSX.utils.table_to_book(
                                        document.getElementById('echarts_' + type)
                                    );
                                    console.log(et)
                                    let etout = XLSX.write(et, {
                                        bookType: "xlsx",
                                        bookSST: true,
                                        type: "array",
                                    });
                                    try {
                                        openDownloadDialog( new Blob([etout], {
                                            type: "application/octet-stream",
                                        }), '统计数据.xlsx');
                                        // FileSaver.saveAs(
                                        //     new Blob([etout], {
                                        //         type: "application/octet-stream",
                                        //     }),
                                        //     "头部文件名" + "-" + new Date().toLocaleString() +".xlsx"
                                        // );
                                    } catch (e) {
                                    }
                                    return etout;

                                },
                            },
                            magicType: {show: true},
                            saveAsImage: {show: true},
                        }
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: data.column,
                    },
                    yAxis: {
                        boundaryGap: [0, '100%'],
                        type: 'value'
                    },
                    grid: [{
                        left: '3%',
                        top: '1%',
                        right: '3%',
                        bottom: '0',
                        containLabel: true
                    }],
                    series: series
                };
                // 使用刚指定的配置项和数据显示图表。
                myChart.setOption(option, true);

                $(window).resize(function () {
                    myChart.resize();
                });
            },
        }
    };

    return Controller;
});
function btn_export() {
    var table1 = document.querySelector("#table1");
    var sheet = XLSX.utils.table_to_sheet(table1);//将一个table对象转换成一个sheet对象
    openDownloadDialog(sheet2blob(sheet), '导出.xlsx');
}

// 将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
function sheet2blob(sheet, sheetName) {

    sheetName = sheetName || 'sheet1';
    var workbook = {
        SheetNames: [sheetName],
        Sheets: {}
    };
    workbook.Sheets[sheetName] = sheet; // 生成excel的配置项

    var wopts = {
        bookType: 'xlsx', // 要生成的文件类型
        bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
        type: 'binary'
    };
    var wbout = XLSX.write(workbook, wopts);
    var blob = new Blob([s2ab(wbout)], {
        type: "application/octet-stream"
    }); // 字符串转ArrayBuffer
    function s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    }
    return blob;
}

function openDownloadDialog(url, saveName) {
    if (typeof url == 'object' && url instanceof Blob) {
        url = URL.createObjectURL(url); // 创建blob地址
    }
    var aLink = document.createElement('a');
    aLink.href = url;
    aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
    var event;
    if (window.MouseEvent) event = new MouseEvent('click');
    else {
        event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    }
    aLink.dispatchEvent(event);
}
